package com.bestv.search.engine.compass.extend;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.compass.core.*;
import org.compass.core.config.CompassSettings;
import org.compass.core.impl.DefaultCompassSession;
import org.compass.core.impl.ExistingCompassSession;

public class CompassTemplateExtend extends CompassTemplate {

    private static Log log = LogFactory.getLog(CompassTemplateExtend.class);
    private CompassSettings globalSessionSettings = new CompassSettings();

    public CompassTemplateExtend(Compass compass) {
        super(compass);
    }

    @Override
    public <T> T execute(CompassCallback<T> action) throws CompassException {
        CompassSession session = getCompass().openSession();
        DefaultCompassSessionExtend sessionExd = new DefaultCompassSessionExtend(
                (DefaultCompassSession) session);
        sessionExd.getSettings().addSettings(globalSessionSettings);
        CompassTransaction tx = null;
        try {
            tx = sessionExd.beginTransaction();
            T result = action
                    .doInCompass(new ExistingCompassSession(sessionExd));
            tx.commit();
            return result;
        } catch (RuntimeException e) {
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (Exception e1) {
                    log.error("Failed to rollback transaction, ignoring", e1);
                }
            }
            throw e;
        } catch (Error err) {
            if (tx != null) {
                try {
                    tx.rollback();
                } catch (Exception e1) {
                    log.error("Failed to rollback transaction, ignoring", e1);
                }
            }
            throw err;
        } finally {
            sessionExd.close();
            session.close();
        }
    }

}
